package com.kj.platformlogistics.home.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kj.platformlogistics.R;
import com.kj.platformlogistics.base.BaseVPFragment;
import com.kj.platformlogistics.constants.UrlConstants;
import com.kj.platformlogistics.home.activity.AllHistoryOrderListActivity;
import com.kj.platformlogistics.home.activity.WaitSolicilationDetailActivity;
import com.kj.platformlogistics.home.adapter.AllHistoryOrderAdapter;
import com.kj.platformlogistics.home.adapter.WaitSolicilationAdapter;
import com.kj.platformlogistics.home.model.AllHistoryOrderList;
import com.kj.platformlogistics.home.model.SolicilationedModel;
import com.kj.platformlogistics.home.model.WaitSolicilationListModel;
import com.kj.platformlogistics.http.HttpRequest;
import com.kj.platformlogistics.http.HttpStringCallBack;
import com.kj.platformlogistics.util.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.kj.platformlogistics.constants.Constants.PAGESIZE;

public class WaitSolicilationFragment extends BaseVPFragment {
    private WaitSolicilationAdapter adapter;
    private RecyclerView rcView;
    private View view;
    private Context context;
    private List<SolicilationedModel.ResultDTO.PageDTO> data;
    private LinearLayout llNodata;

    private int currentPage=1;
    private SmartRefreshLayout refresh;
    private int count=0;
    private int status=0;
    private int type=0;

    public static WaitSolicilationFragment newInstance(int type ,int status ) {
        Bundle arguments = new Bundle();
        arguments.putInt("status",status);
        arguments.putInt("type",type);
        WaitSolicilationFragment fl = new WaitSolicilationFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_wait_solicilation, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            if(!EventBus.getDefault().isRegistered(this)){//加上判断
                EventBus.getDefault().unregister(this);
            }
        }
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if(!isVisible){
            //不可见
            if(!EventBus.getDefault().isRegistered(this)){//加上判断
                EventBus.getDefault().unregister(this);
            }
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
    }

    public void initView(){
        status=getArguments().getInt("status",0);
        type=getArguments().getInt("type",0);
        refresh=view.findViewById(R.id.refresh);
        rcView=view.findViewById(R.id.rcView);
        llNodata=view.findViewById(R.id.llNodata);

        setView();
        getData();

    }


    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(PAGESIZE));
            map.put("status",status);
            map.put("type",type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.logistics_getOrderListByStatus, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), SolicilationedModel.class);
                        if (obj instanceof SolicilationedModel) {
                            SolicilationedModel model=(SolicilationedModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getPage().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcView.setVisibility(View.VISIBLE);
                                    data=model.getResult().getPage();
                                    adapter=new WaitSolicilationAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            WaitSolicilationDetailActivity.actionStart(context,data.get(position));
                                        }
                                    });

                                } else {
                                    rcView.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                }
                            } else {
                                data.addAll(model.getResult().getPage());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }
}
